package tool

import (
	"gitee.com/tjloved/tool/db"
	"gitee.com/tjloved/tool/logger"
	"gorm.io/gorm"
	"sync"
)

var dbMap sync.Map

func Db(connection ...string) *gorm.DB {
	connectionName := "default"
	if len(connection) > 0 {
		connectionName = connection[0]
	}
	if _, ok := dbMap.Load(connectionName); !ok {
		config := db.NewConfig()
		if err := Config().UnmarshalKey("mysql."+connectionName, &config); err != nil {
			panic(err)
		}
		config.Logger = logger.NewGormZapLoggerAdapter(Logger("mysql"), *config)
		dbMap.Store(connectionName, db.New(config))
	}
	c, _ := dbMap.Load(connectionName)
	if client, ok := c.(*gorm.DB); ok {
		return client
	} else {
		panic("mysql 初始化错误")
	}
}
